<template>
  <div class="product-add-container">
    <el-card class="box-card">
      <template #header>
        <div class="card-header">
          <span>添加商品</span>
        </div>
      </template>

      <el-form :model="productForm" label-width="120px">
        <el-form-item label="商品名称">
          <el-input v-model="productForm.title" placeholder="请输入商品名称"></el-input>
        </el-form-item>

        <el-form-item label="商品描述">
          <el-input
            v-model="productForm.description"
            type="textarea"
            :rows="3"
            placeholder="请输入商品描述"
          ></el-input>
        </el-form-item>

        <el-form-item label="商品分类">
          <el-cascader
            :options="categoryStore.categoryList"
            v-model="categoryId"
            placeholder="请选择商品分类"
            :props="{
              checkStrictly: true,
              value: 'categoryId',
              label: 'name',
              children: 'children',
            }"
          ></el-cascader>
        </el-form-item>

        <el-form-item label="商品价格">
          <el-input-number
            v-model="productForm.price"
            :min="0"
            placeholder="请输入商品价格"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="商品库存">
          <el-input-number
            v-model="productForm.stock"
            :min="0"
            placeholder="请输入商品库存"
          ></el-input-number>
        </el-form-item>

        <el-form-item label="是否上架">
          <el-radio-group v-model="productForm.isVirtual">
            <el-radio :label="1">是</el-radio>
            <el-radio :label="0">否</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="主图上传">
          <!-- <el-upload
            class="upload-demo"
            drag
            :action="uploadUrl"
            :on-success="handleMainImageUpload"
            :before-upload="beforeUpload"
            :show-file-list="false"
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">拖拽上传</div>
          </el-upload>
          <div v-if="productForm.mainImage" class="image-preview">
            <img :src="productForm.mainImage" alt="预览图" />
          </div> -->
          <el-upload
            action=""
            :file-list="mainImage"
            :http-request="mainUploadImage"
            :on-success="mainUploadSuccess"
            :on-remove="mainRemoveImage"
            list-type="picture-card"
            :limit="1"
            :on-exceed="mainExceed"
            :before-upload="mainBeforeUpload"
          >
            <i class="el-icon-plus"></i>
            <div class="el-upload__text">点击上传</div>
          </el-upload>
        </el-form-item>

        <el-form-item label="图片上传">
          <!-- <el-upload
            class="upload-demo"
            drag
            :action="uploadUrl"
            :on-success="handleImageUpload"
            :before-upload="beforeUpload"
            multiple
          >
            <el-icon class="el-icon--upload"><upload-filled /></el-icon>
            <div class="el-upload__text">拖拽上传</div>
          </el-upload>
          <div class="image-preview-list">
            <img
              v-for="(image, index) in productForm.images"
              :key="index"
              :src="image"
              alt="预览图"
            />
          </div> -->
          <el-upload
            action=""
            :file-list="productForm.images"
            :http-request="uploadImage"
            :on-success="handleUploadSuccess"
            :on-remove="handleRemoveImage"
            :on-exceed="handleExceed"
            :before-upload="beforeUpload"
            list-type="picture-card"
            :limit="5"
          >
            <i class="el-icon-plus"></i>
            <div class="el-upload__text">点击上传</div>
          </el-upload>
        </el-form-item>

        <el-form-item>
          <el-button type="primary" @click="submitForm">添加商品</el-button>
        </el-form-item>
      </el-form>
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted, watch } from "vue";
import { ElMessage } from "element-plus";
import { useCategoryStore } from "@/stores/category";
import {addProduct, autoReviewProduct} from "@/apis/product";
import { uploadImg } from "@/apis/upload";
import { computed } from "vue";
import { userInfoStore } from "@/stores/user";

const categoryStore = useCategoryStore();
const uploadUrl = ref(import.meta.env.VITE_API_BASE_URL + "/upload");

const productForm = ref({
  userId: userInfoStore().userInfo.userId,
  title: "",
  description: "",
  categoryId: null,
  price: 0,
  stock: 0,
  isVirtual: 1,
  mainImage: "",
  images: [],
});

const categoryId = ref([]);

const lastElement = computed(() => {
  return categoryId.value.length > 0
    ? categoryId.value[categoryId.value.length - 1]
    : undefined;
});
watch(
  () => categoryId.value,
  () => {
    console.log("categoryId ", categoryId.value);
    productForm.value.categoryId = lastElement.value;
    console.log("categoryId ", productForm.value.categoryId);
  }
);

const mainImage = ref([]);
// 上传图片相关
const mainUploadImage = async (options) => {
  const { file } = options;
  const formData = new FormData();
  formData.append("file", file);

  try {
    const res = await uploadImg(formData);
    if (res.code === 200) {
      options.onSuccess(res.message);
    } else {
      options.onError(new Error("上传失败"));
    }
  } catch (error) {
    options.onError(new Error("上传出错"));
    console.error(error);
  }
};

const mainUploadSuccess = (response, uploadFile) => {
  console.log("response: ", response);
  if (response) {
    mainImage.value.push(response);
    productForm.value.mainImage = mainImage.value[0];
  }
};

const mainRemoveImage = (file, fileList) => {
  console.log("fileList: ", fileList);
  mainImage.value = fileList;
  productForm.value.images = "";
};

const mainExceed = (files, fileList) => {
  ElMessage.warning(`最多只能上传1张图片`);
};

const mainBeforeUpload = (rawFile) => {
  const isJPG = rawFile.type === "image/jpeg";
  const isPNG = rawFile.type === "image/png";
  const isLt2M = rawFile.size / 1024 / 1024 < 5;

  if (!isJPG && !isPNG) {
    ElMessage.error("只能上传JPG或PNG格式的图片");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过2MB");
    return false;
  }
  return true;
};

// 上传图片相关
const uploadImage = async (options) => {
  const { file } = options;
  const formData = new FormData();
  formData.append("file", file);

  try {
    const res = await uploadImg(formData);
    if (res.code === 200) {
      options.onSuccess(res.message);
    } else {
      options.onError(new Error("上传失败"));
    }
  } catch (error) {
    options.onError(new Error("上传出错"));
    console.error(error);
  }
};

const handleUploadSuccess = (response, uploadFile) => {
  console.log("response: ", response);
  if (response) {
    productForm.value.images.push(response);
  }
};

const handleRemoveImage = (file, fileList) => {
  console.log("fileList: ", fileList);
  productForm.value.images = fileList;
};

const handleExceed = (files, fileList) => {
  ElMessage.warning(`最多只能上传5张图片`);
};

const beforeUpload = (rawFile) => {
  const isJPG = rawFile.type === "image/jpeg";
  const isPNG = rawFile.type === "image/png";
  const isLt2M = rawFile.size / 1024 / 1024 < 5;

  if (!isJPG && !isPNG) {
    ElMessage.error("只能上传JPG或PNG格式的图片");
    return false;
  }
  if (!isLt2M) {
    ElMessage.error("图片大小不能超过2MB");
    return false;
  }
  return true;
};

// 提交表单
const submitForm = () => {

  addProduct(productForm.value)
      .then(res => {

        autoReviewProduct({
          productId: res.data.productId,
          title: res.data.title,
          description: res.data.description,
          tags: res.data.tags
        })

        ElMessage.success("商品添加成功");
        // 清空表单
        categoryId.value = [];
        mainImage.value = [];
        productForm.value = {
          userId: userInfoStore().userInfo.userId,
          title: "",
          description: "",
          categoryId: null,
          price: 0,
          stock: 0,
          isVirtual: 1,
          mainImage: "",
          images: [],
        };
  })
};

onMounted(() => {
  // 确保分类数据已加载
  if (categoryStore.categoryList.length === 0) {
    // 如果你的分类数据需要通过API获取，请在这里调用相应的API
    // categoryStore.fetchCategories();
  }
});
</script>

<style scoped lang="scss">
.product-add-container {
  margin: 20px;
}

.card-header {
  font-size: 18px;
  font-weight: bold;
}

.image-preview {
  margin-top: 10px;
  img {
    max-width: 100%;
    max-height: 200px;
  }
}

.image-preview-list {
  margin-top: 10px;
  display: flex;
  flex-wrap: wrap;
  img {
    width: 100px;
    height: 100px;
    margin-right: 10px;
    margin-bottom: 10px;
  }
}
</style>
